package com.sinogrand.elevator.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import com.sinogrand.elevator.utils.EnvironmentManager
import com.sinogrand.elevator.utils.LogTags
import android.util.Log
import android.widget.Toast

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EnvironmentSwitchScreen(
    onNavigateBack: () -> Unit,
    onEnvironmentChanged: () -> Unit
) {
    val context = LocalContext.current
    val environmentManager = remember { EnvironmentManager(context) }
    
    // 状态管理
    var currentEnvironment by remember { mutableStateOf(environmentManager.getCurrentEnvironment()) }
    var showConfirmDialog by remember { mutableStateOf(false) }
    var selectedEnvironment by remember { mutableStateOf("") }
    
    // 获取所有环境配置
    val allEnvironments = environmentManager.getAllEnvironments()
    
    // 切换环境的函数
    fun switchEnvironment(environment: String) {
        if (environment != currentEnvironment) {
            selectedEnvironment = environment
            showConfirmDialog = true
        }
    }
    
    // 确认切换环境
    fun confirmSwitchEnvironment() {
        try {
            // 清空环境数据
            environmentManager.clearEnvironmentData()
            
            // 设置新环境
            environmentManager.setEnvironment(selectedEnvironment)
            
            // 更新当前环境状态
            currentEnvironment = selectedEnvironment
            
            // 清空登录信息
            val tokenManager = com.sinogrand.elevator.utils.TokenManager(context)
            tokenManager.clearUserInfo()
            
            Log.i(LogTags.ENVIRONMENT_MANAGER, "✅ 环境切换完成: ${allEnvironments[selectedEnvironment]?.name}")
            
            // 显示成功提示
            Toast.makeText(context, "环境已切换到${allEnvironments[selectedEnvironment]?.name}，请重新登录", Toast.LENGTH_LONG).show()
            
            // 关闭确认对话框
            showConfirmDialog = false
            
            // 通知外部环境已改变
            onEnvironmentChanged()
            
        } catch (e: Exception) {
            Log.e(LogTags.ENVIRONMENT_MANAGER, "❌ 环境切换失败: ${e.message}", e)
            Toast.makeText(context, "环境切换失败: ${e.message}", Toast.LENGTH_SHORT).show()
            showConfirmDialog = false
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(
                Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFFF8FAFC),
                        Color(0xFFF1F5F9)
                    )
                )
            )
    ) {
        // 顶部导航栏
        TopAppBar(
            title = {
                Text(
                    text = "环境切换",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1F2937)
                )
            },
            navigationIcon = {
                IconButton(onClick = onNavigateBack) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                        contentDescription = "返回"
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = Color.White,
                titleContentColor = Color(0xFF1F2937),
                navigationIconContentColor = Color(0xFF1F2937)
            ),
            modifier = Modifier.shadow(2.dp)
        )
        
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 当前环境信息卡片
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(containerColor = Color.White),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                shape = RoundedCornerShape(16.dp)
            ) {
                Column(
                    modifier = Modifier.padding(20.dp)
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = null,
                            tint = Color(0xFF3B82F6),
                            modifier = Modifier.size(24.dp)
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Text(
                            text = "当前环境",
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF1F2937)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    val currentConfig = environmentManager.getCurrentEnvironmentConfig()
                    Text(
                        text = currentConfig.name,
                        fontSize = 24.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF3B82F6)
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "API地址: ${currentConfig.baseUrl}",
                        fontSize = 14.sp,
                        color = Color(0xFF6B7280)
                    )
                    
                    Spacer(modifier = Modifier.height(4.dp))
                    
                    Text(
                        text = "审批流程: ${currentConfig.approvalFlowUrl}",
                        fontSize = 14.sp,
                        color = Color(0xFF6B7280)
                    )
                }
            }
            
            // 环境选择列表
            Text(
                text = "选择环境",
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF1F2937)
            )
            
            allEnvironments.forEach { (envKey, config) ->
                EnvironmentCard(
                    environmentKey = envKey,
                    config = config,
                    isSelected = envKey == currentEnvironment,
                    onClick = { switchEnvironment(envKey) }
                )
            }
            
            // 说明信息
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(containerColor = Color(0xFFFEF3C7)),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                shape = RoundedCornerShape(12.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.Warning,
                            contentDescription = null,
                            tint = Color(0xFFD97706),
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "注意事项",
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFFD97706)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "• 切换环境后会自动清空登录信息\n• 需要重新登录才能使用新环境\n• 不同环境的数据是独立的",
                        fontSize = 12.sp,
                        color = Color(0xFF92400E),
                        lineHeight = 18.sp
                    )
                }
            }
        }
    }
    
    // 确认切换对话框
    if (showConfirmDialog) {
        AlertDialog(
            onDismissRequest = { showConfirmDialog = false },
            title = {
                Text(
                    text = "确认切换环境",
                    fontWeight = FontWeight.Bold
                )
            },
            text = {
                val selectedConfig = allEnvironments[selectedEnvironment]
                Column {
                    Text(
                        text = "确定要切换到 ${selectedConfig?.name} 吗？",
                        fontSize = 16.sp
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "切换后需要重新登录",
                        fontSize = 14.sp,
                        color = Color(0xFF6B7280)
                    )
                }
            },
            confirmButton = {
                TextButton(
                    onClick = { confirmSwitchEnvironment() },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = Color(0xFFDC2626)
                    )
                ) {
                    Text("确认切换")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { showConfirmDialog = false }
                ) {
                    Text("取消")
                }
            }
        )
    }
}

@Composable
fun EnvironmentCard(
    environmentKey: String,
    config: com.sinogrand.elevator.utils.EnvironmentConfig,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected) Color(0xFFEFF6FF) else Color.White
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = if (isSelected) 6.dp else 2.dp
        ),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 环境图标
            Icon(
                imageVector = if (environmentKey == com.sinogrand.elevator.utils.EnvironmentManager.ENVIRONMENT_PRODUCTION) 
                    Icons.Default.Cloud else Icons.Default.DeveloperMode,
                contentDescription = null,
                tint = if (isSelected) Color(0xFF3B82F6) else Color(0xFF6B7280),
                modifier = Modifier.size(24.dp)
            )
            
            Spacer(modifier = Modifier.width(16.dp))
            
            // 环境信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = config.name,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = if (isSelected) Color(0xFF3B82F6) else Color(0xFF1F2937)
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Text(
                    text = config.baseUrl,
                    fontSize = 12.sp,
                    color = Color(0xFF6B7280)
                )
            }
            
            // 选中状态指示器
            if (isSelected) {
                Icon(
                    imageVector = Icons.Default.CheckCircle,
                    contentDescription = "已选中",
                    tint = Color(0xFF3B82F6),
                    modifier = Modifier.size(24.dp)
                )
            }
        }
    }
}
